# Used to call all other controllers
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  # protect_from_forgery # :secret => '450a532f34227e7b55f62f6abc2ea79a'
  
  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  # filter_parameter_logging :password
  layout "facebook"
  
  filter_parameter_logging :password
  ensure_authenticated_to_facebook [:except=>["buy_point","from_chat","adparlor"]]

  helper_method :facebook_session
  helper_method :render_to_string 
  helper_method :last_log

  before_filter :current_user,:except=>[:buy_point,:from_chat,:adparlor]  
  before_filter :set_app_name,:except=>[:buy_point,:from_chat,:adparlor]  
  before_filter :update_friends,:except=>[:buy_point,:from_chat,:adparlor]  
  before_filter :add_log
  def last_log
    logs = Ilog.find(:all,:conditions=>["user_id = ?",current_user.id],:order=>'id desc',:limit=>2)
    last_log = logs.first
  end 
  # Add a log when a page is open or any action (for app analytics)
  def add_log
    uid = params[:uid]
   if params[:uid].to_i > 0
     cur_user = User.find(params[:uid]) 
   else
     cur_user = current_user
   end
   from = 5 # Other
   if params[:from] == "bookmark"
     from = 4 
   elsif params[:from] == "notification"
     from = 3
   elsif params[:from] == "email"
     from = 2
   elsif params[:fb_sig_ext_perms] == "auto_publish_recent_activity"
     from = 1
   end
    logger.error "======================================"
    logger.error controller_name +  ":" + action_name
    logger.error request.env['HTTP_REFERER']
    logger.error "======================================"
    # Try to find one
    logs = Ilog.find(:all,:conditions=>["user_id = ?",cur_user.id],:order=>'id desc',:limit=>2)
    last_log = logs.first
    last_last_log = nil
    last_last_log = logs.last if logs.size > 1
    if logs.size > 0
       if Time.now - last_log.updated_at <  60 * 120 # sesstion time: seconds * mins
	 last_log.time_on_site = Time.now - last_log.created_at
	 last_log.pages_per_visit += 1 if action_name=="index"
	 last_log.no_of_clicks += 1 
	 #last_log.no_of_bets += 1  if action_name == "create" and controller_name == "bets"
	 last_log.no_of_comments += 1  if params[:fb_sig_xid_action] == "post"
	 last_log.no_of_challenges += 1  if (controller_name == "friends_bet" and action_name == "sent") or (controller_name == "bets" and action_name == "create" and params[:to_user_id])
	 last_log.no_of_accept += 1  if (controller_name == "friends_bet" and action_name == "accept")
	 last_log.refer_via_comment += 1  if params[:fb_sig_ext_perms] == "auto_publish_recent_activity"
	 last_log.invite_via_earn += params[:ids].size  if params[:ids]
         last_log.reward1_amt += params[:credit].to_i if controller_name == "srpoint" and action_name == "adparlor"
         last_log.reward2_amt += params[:new].to_i if controller_name == "srpoint" and action_name == "buy_point"

	 last_log.save
         name = controller_name + ":" + action_name 
         name += ":Basketball"  if controller_name == "sports" and params[:id] == "3" and action_name == "show"
         name += ":Football"  if controller_name == "sports" and action_name == "show" and params[:id] == "3"
         name += "-filter:" + params[:filter] if params[:filter] 
         name += "-orderby:" + params[:order_by] if params[:order_by] 
         name += "-level:" + params[:level] if params[:level] 
         name += "-type:" + params[:type] if params[:type] 
         IlogAction.create!(:ilog_id=>last_log.id,:name=>name)
       else
	# New log
	 new_log(last_last_log,cur_user,from)
       end
    else
      # New log
       new_log(last_last_log,cur_user,from)
    end 
  end
  
  # New log when a page is open or action (for app analytics)
  def new_log(last_last_log,current_user,from)
    Ilog.create!(:user_id=>current_user.id,
		:which_revisit =>from, 
		:pages_per_visit=>1, 
		:time_on_site=>0, 
		:no_of_clicks=>0, 
		:no_of_bets=>0, 
		:no_of_comments=>0, 
		:no_of_challenges=>0, 
		:no_of_accept =>0, 
		:days_since_1st_visit=> ((Time.now - current_user.created_at) / (24*60*60)).round , 
		:days_since_last_visit=>last_last_log.nil? ? 0 : ((Time.now - last_last_log.updated_at) / (24*60*60)).round, 
		:total_bets=>current_user.bets.size, 
		:current_streak=>(current_user.current_winstreak_count rescue 0), 
		:best_streak=>(current_user.best_winstreak.streak_count rescue 0), 

		:invite_via_earn=>0, 
		:refer_via_comment=>0, 
		:invite_via_challenge=>0, 
		:reward1_amt=>0, 
		:reward2_amt=>0) 
    logger.error "================================================new log created!!!!!!!!!!!!!!!!!!!!!!"
  end
  
  # Current user or create a new user if does not exist
  def current_user
    @current_user ||= User.for(facebook_session)
  end

  def initialize
    @odd = 0
  end 
  
  # Set @appname and @call_back_url from envorionments config
  def set_app_name
    @app_name = Facebooker.facebooker_config["canvas_page_name"]
    @call_back_url = Facebooker.facebooker_config["callback_url"].gsub("http://","")
  end

  # Update firends_ids field if null
  def update_friends
    if (current_user.friends_count.nil? or current_user.friends_count.to_i == 0) or (current_user.friends_count.to_i < params[:fb_sig_friends].to_s.split(",").size)
       current_user.all_friends = params[:fb_sig_friends]
       current_user.friends_count = params[:fb_sig_friends].to_s.split(",").size
       current_user.save
    end
	
	#update user profile if it has been 180 days since last update
    if (((Time.now - current_user.updated_at) / (24*60*60)).round > 180)	
		user = current_user
	    user.last_name         = facebook_session.user.last_name                                                 
	    user.first_name        = facebook_session.user.first_name
	    user.name			   = facebook_session.user.name
	    user.affiliations      = facebook_session.user.affiliations.map{|a| a.year + ":" + a.name}.join(";") if facebook_session.user.affiliations        
	    user.timezone          = facebook_session.user.timezone 
	    user.birthday          = facebook_session.user.birthday                                                    
	    user.sex          	   = facebook_session.user.sex               
	    user.current_location = (facebook_session.user.current_location.city rescue "") + "," +  (facebook_session.user.current_location.state rescue "") + "," + (facebook_session.user.current_location.country rescue "")  if facebook_session.user.current_location
	    user.activities        = facebook_session.user.activities        
	    user.interests         = facebook_session.user.interests                                                 
	    user.hs_info           = facebook_session.user.hs_info.hs1_name if facebook_session.user.hs_info
	    user.education_history = facebook_session.user.education_history.map{|h| h.name}.join(";")   if facebook_session.user.education_history
	    user.work_history      = facebook_session.user.work_history.map{|h| h.company_name + ":" + h.position}.join(";") if facebook_session.user.work_history        
	    user.wall_count        = facebook_session.user.wall_count        
		user.save
	end
  end

  # Deliver a challenge notification 
  def deliver_notify
    logger.error "==========================="
    logger.error NotificationPublisher.deliver_challenge(current_user.sent_challenges.first) if current_user.sent_challenges.size > 0
    logger.error "==========================="
  end

  helper_method :current_user

end
